package com.softserveinc.fragments;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;

import com.softserveinc.R;
import com.softserveinc.fragments.adapter.MovieFragmentAdapter;
import com.viewpagerindicator.TitlePageIndicator;
import com.viewpagerindicator.TitlePageIndicator.IndicatorStyle;

public class MovieListStorageFragment extends Fragment {

	protected static final String TAG = MovieListStorageFragment.class
			.getSimpleName();

	private MovieFragmentAdapter fragmentAdapter;
	private ViewPager pager;
	private TitlePageIndicator indicator;
	private View viewpagerHolder;
	private View fragmentHolder;

	@Override
	public void onActivityCreated(final Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		viewpagerHolder = getActivity().findViewById(R.id.viewpager_holder);
		fragmentHolder = getActivity().findViewById(R.id.frame_for_fragment);

		pager = (ViewPager) viewpagerHolder.findViewById(R.id.pager);

		if (pager.getAdapter() == null) {
			fragmentAdapter = new MovieFragmentAdapter(
					getSupportFragmentManager(), 0);

			pager.setAdapter(fragmentAdapter);

			indicator = (TitlePageIndicator) viewpagerHolder
					.findViewById(R.id.indicator);
			indicator.setViewPager(pager);

			decoreIndicator();

			setIndicatorListener();
		}

		fragmentHolder.setVisibility(View.GONE);
		viewpagerHolder.setVisibility(View.VISIBLE);
	}

	private void setIndicatorListener() {
		indicator.setOnPageChangeListener(new OnPageChangeListener() {

			private int previousPosition = -1;

			@Override
			public void onPageSelected(final int position) {
			}

			@Override
			public void onPageScrolled(final int position,
					final float positionOffset, final int positionOffsetPixels) {
				if (positionOffsetPixels == 0) {
					fragmentAdapter.updateData(position, previousPosition);

					previousPosition = position;
				}
			}

			@Override
			public void onPageScrollStateChanged(final int state) {
			}
		});
	}

	private void decoreIndicator() {
		float density = getResources().getDisplayMetrics().density;

		indicator.setBackgroundColor(Color.WHITE);
		indicator.setFooterColor(Color.BLACK);
		indicator.setFooterLineHeight(1 * density);
		indicator.setFooterIndicatorHeight(1 * density);
		indicator.setFooterIndicatorStyle(IndicatorStyle.Underline);
		indicator.setTextColor(0xAA000000);
		indicator.setSelectedColor(0xFF000000);
		indicator.setSelectedBold(true);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();

		viewpagerHolder.setVisibility(View.GONE);
		fragmentHolder.setVisibility(View.VISIBLE);
	}
}
